<?php
namespace app\middleware;

use Closure;
use think\Request;

/**
 * 跨域中间件
 */
class Cors
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param Closure        $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        // 设置 CORS 相关响应头
        header('Access-Control-Allow-Origin: *'); // 开发阶段允许所有来源
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

        // 如果是预检请求（OPTIONS），直接返回 204
        if ($request->isOptions()) {
            return response('', 204);
        }

        $response = $next($request);

        return $response;
    }
}